from AuxLibraries import *
import GWPs
import auxiliars as aux
import MakeFigures 
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)


'''
This is the main function that can be used to replicate the results

'''
SAR =GWPs.get_SAR()
TAR =GWPs.get_TAR()
AR4 =GWPs.get_AR4()
AR5 =GWPs.get_AR5()
AR6 =GWPs.get_AR6()
Z = pd.concat((SAR, TAR, AR4,AR5,AR6))

FG = MakeFigures.FIGURE_()

#%% Load CDP data
dt = aux.get_cdp_data()
#== Light merge with region info (this merging removes a bit of companies but not important ones)
dtm = aux.light_merge(dt, country_merge=True )

#%%
#============================#
#========= Figure 1 =========#
#============================#

#%% Figure 1
'''
This figure illustrates the heterogeneity of the emission metric choise across the sample
'''
relevant_sample = FG.FIGURE1(dt, Z,  save_plot=True)


#%%
#============================#
#========= Figure 2 =========#
#============================#


#%% Counterfactual analysis at 100-year
'''
This figure illustrates the methane conversion gap
'''
plt.figure(figsize=(28, 8))
ax1 = plt.subplot(121)
order, dtGap = FG.FIGURE1B(dt, dtm, Z,  ax1, 'CH4', HORIZON=100, labels = ['a', 'b', 'c'], save_plot=False)
ax2 = plt.subplot(122)
FG.FIGURE1G(dtm, Z, order, ax2, HORIZON=100,labels=['d'], save_plot=False)
plt.tight_layout()
plt.savefig('Figures/Figure1B_100.pdf', dpi = 300, bbox_inches = 'tight')

#%% Counterfactual analysis  at 20-year
plt.figure(figsize=(28, 8))
ax1 = plt.subplot(121)
_, dtGap = FG.FIGURE1B(dt, dtm, Z,  ax1, 'CH4', HORIZON=20, labels = ['e', 'f', 'g'], save_plot=False)
ax2 = plt.subplot(122)
FG.FIGURE1G(dtm, Z, order, ax2,  HORIZON=20,labels=['h'], save_plot=False)
plt.tight_layout()
plt.savefig('Figures/Figure1B_20.pdf', dpi = 300, bbox_inches = 'tight')

#%%
#===============================================================
#=== Figures for the SI that refer to Figure 1 in the main text
#===============================================================
#%% Breakdown of the count of the disclosure
FG.Figure0_SI(dt, save_plot=True)
#%% Proportion of standard followers
FG.Figure1_SI(dtm, save_plot=True)

#%% Proportion of Methane emissions over total Scope 1
sector_choice = 'main_sector'
sector_order = FG.FIGURE2_SI(dtm, Z, sector_type = sector_choice, save_plot=True)

#===============================================================
#===============================================================
#===============================================================


#%%
#============================#
#========= Figure 3 =========#
#============================#

#%% YoY change in emission by GWP choice
'''
This figure shows the everage change in emissions upon a change in emission metric
compared to the average change in emission in the same period under an harmonised counterfactual
'''
save_it=True
change_type = 'first_differences'
for HRZ in [20, 100]:
    DAH, AH, BH = FG.FIGURE3(dtm, Z, HORIZON=HRZ, dimension_change='Horizon', GASD='CH4', change_type = change_type, panel = ['', ''], LABEL = 'A', save_plot=save_it)
    DAR, AR, BR = FG.FIGURE3(dtm, Z, HORIZON=HRZ, dimension_change='AR', GASD='CH4', change_type = change_type, panel = ['', ''], LABEL = 'B', save_plot=save_it)
    FG.PLOTFIGURE3(HRZ, AH, BH, AR, BR, save_plot=save_it)
    print('#==========')
    print("Proportion of companies not changing Horizon:", np.mean(DAH['No change'].dropna()/DAH.dropna().sum(axis = 1)))
    print("Proportion of companies not changing AssRep.:", np.mean(DAR['No change'].dropna()/DAR.dropna().sum(axis = 1)))
    print('#==========')

#%%
#============================#
#========= Figure 4 =========#
#============================#
#%%
'''
Analysis of etransition risks associated with the methane conversion gap
'''
resEI = []
resTR = []
order=-1
for HRZ in [100, 20]:
    econ_impc, tnrisk, order = FG.FIGURE4(dtm, dt, Z,order,GAS='CH4', save_plot=True, HORIZON=HRZ, LOGscale=True)
    resEI.append(econ_impc)
    resTR.append(tnrisk)
print('Max earnings at risk under the GWP100 counterfactual:', 
      str(np.round(resTR[0].sort_values(by = 'differential_risk').reset_index(drop=True)[['Cost', 'CounterfactualCost']], 2).iloc[-10:]),'%')
print('Max earnings at risk under the GWP20 counterfactual:', 
      str(np.round(resTR[1].sort_values(by = 'differential_risk').reset_index(drop=True)[['Cost', 'CounterfactualCost']], 2).iloc[-10:]),'%')



